<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\City;
use think\facade\Log;

class CityService
{
    /**
     * 列表
     * @return void
     */
    public function getCityList()
    {
        $model = new City();
        return $model->order(['arealevel'=>'desc'])->paginate(MAX_SIZE);
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        if (empty($data)) {
            return false;
        }
        try {
            $model = new City();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit city error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'( ⊙ o ⊙ )！服务器反应不过来了，请稍后再试，'. $e->getMessage()]);
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        $model = new City();
        return $model::destroy($id);
    }

    /**
     * 查询一条记录
     * @param int $id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne(int $id)
    {
        $model = new City();
        return $model->find($id);
    }

    /**
     * 获取城市列表
     * @param int $cityId
     * @return mixed
     */
    public function getCitys(int $cityId = 0)
    {
        $model = new City();
        if($cityId){
            return  $model->field('id,title_name')->where('parent_id', $cityId)->order(['id'=>'asc'])->select();
        } else{
            return  $model->field('id,title_name')->where('parent_id', 0)->order(['id'=>'asc'])->select();
        }
    }

    /**
     * 获取城市id
     * @param int $cityId
     * @return mixed
     */
    public function getCityParentId(int $cityId = 0): mixed
    {
        $model = new City();
        return $model->where('id', $cityId)->value('parent_id');
    }
}